package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.WhitesIgnoreConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName AuthFilter
 * @Description 描述
 * @Author ShiYu.Cui
 * @Date 2024/4/25 9:41
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private WhitesIgnoreConfig whitesIgnoreConfig;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> whites = whitesIgnoreConfig.getWhites();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(StringUtils.matches(path,whites)){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        if(StringUtils.isBlank(token)){
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }
        try{
            JwtUtils.parseToken(token);
        }catch (Exception e){
            return GatewayUtils.errorResponse(exchange,"token不合法");
        }
        String userKey = JwtUtils.getUserKey(token);
        if(!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"token失败");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
